package linuxbox.calendar.taglib;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import javax.servlet.http.*;

import linuxbox.common.BoxSession;
import linuxbox.util.WebTools;
import linuxbox.common.BoxConfigUtil;
import linuxbox.BoxStatic;
/**
 * This class list the todo categories in the SELECT tag.
 */
public class CalendarCatList extends TagSupport
{
	protected boolean showAllCategories = true;
	protected boolean showSystemCat = true;
	protected String selected = null;
	protected int userid = -1;

	public int doStartTag() throws JspException
	{
		try
		{
			JspWriter out = pageContext.getOut();
      BoxSession sec = WebTools.getBoxSession((HttpServletRequest)pageContext.getRequest());
      if (showAllCategories)
      {
  		  if ( selected == null || selected.length()==0 )
          out.print("<option selected value=\"\">All Categories</option>");
        else
          out.print("<option value=\"\">All Categories</option>");
        out.print("<option value=\"\"></option>");
      }

      //The seperator is only added when both categories are exist.
      boolean hasSystemCat = false;
      String[] cats=null;
      if (showSystemCat)
      {
        cats = BoxStatic.mainConfig.getModule("calendar").getConfigValues("Event Category", "Categories");
        if (cats!=null && cats.length >0)
        {
          for(int i=0; i< cats.length; i++)
          {
            if ( selected != null && cats[i].compareTo(selected)==0)
              out.print("<option selected value="+cats[i]+">"+cats[i]+"</option>");
            else
              out.print("<option value="+cats[i]+">"+cats[i]+"</option>");
          }
          hasSystemCat = true;
        }
      }

      if (userid == sec.getID())
      {
        cats = sec.getConfigStrings("calendar", "Event Category", "Categories", false);
      }
      else
        cats = BoxConfigUtil.getUserConfigValues(userid, "calendar", "Event Category", "Categories");

      if (cats!=null && cats.length >0)
      {
        if (hasSystemCat)
          out.print("<option value=\"\"></option>");
        for(int i=0; i< cats.length; i++)
        {
          if ( selected != null && cats[i].compareTo(selected)==0)
            out.print("<option selected value="+cats[i]+">"+cats[i]+"</option>");
          else
            out.print("<option value="+cats[i]+">"+cats[i]+"</option>");
        }
      }

			out.flush();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new JspException(e.getMessage());
		}

		return SKIP_BODY;
	}

	public void setshowallcategories(String aValue)
	{
		showAllCategories = new Boolean(aValue).booleanValue();
	}

	public void setshowsystemcat(String aValue)
	{
		showSystemCat = new Boolean(aValue).booleanValue();
	}

	public void setUserid(int aValue)
	{
		userid = aValue;
	}

	public void setSelected(String aValue)
	{
		selected = aValue;
	}
}
